package com.example.springboot.service.impl;

import cn.hutool.core.date.DateUtil;
import com.example.springboot.Exception.ServiceException;
import com.example.springboot.service.AdminService;
import com.example.springboot.utils.MailUtil;
import com.example.springboot.utils.RandomUtil;
import com.example.springboot.utils.TokenUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 管理员表(Admin)表服务实现类
 *
 * @author makejava
 * @since 2024-01-13 17:16:25
 */
@Service("adminService")
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Resource
    private MailUtil mailUtil;

    @Override
    public Admin login(Account account) {
        // 判断当前用户名是否存在
        Admin adminDB = adminMapper.selectByUsername(account.getUsername());
        // 如果用户不存在，返回不存在信息
        if (adminDB == null) {
            throw new ServiceException("422", "用户不存在！");
        }
        // 判断用户账号密码是否匹配
        if (!adminDB.getPassword().equals(account.getPassword())) {
            throw new ServiceException("488", "用户名或密码错误！");
        }
        if (adminDB.getStatus() == 0) {
            throw new ServiceException("用户已被禁用，请联系管理员！");
        }
        if (adminDB.getStatus() == 2) {
            throw new ServiceException("用户已被锁定，请联系管理员！");
        }
        if (adminDB.getStatus() == 3) {
            throw new ServiceException("用户已被冻结，请联系管理员！");
        }

        // 生成token回传前端
        String token = TokenUtils.genToken(adminDB.getId().toString(), adminDB.getPassword());
        adminDB.setToken(token);
        // 更新数据表的token和最近登陆时间
        Date currentDate = new Date();
        adminDB.setLoginTimeStr(DateUtil.formatDateTime(currentDate));
//        System.out.println(adminDB.toString());
        adminMapper.updateTokenAndLoginTime(adminDB);
        return adminDB;
    }

    @Override
    public Admin register(Account account) {
        // 首先，判断用户输入的账号是否存在，数据库中用户名是唯一的
        Admin dbAdmin = adminMapper.selectByUsername(account.getUsername());
        if (dbAdmin != null) {
            // 用户名已存在，抛出自定义异常
            throw new ServiceException("422", "用户名已存在");
        }
        // 注册==新增用户信息
        try {
            Date currentDate = new Date();
            account.setLoginTimeStr(DateUtil.formatDateTime(currentDate));
            adminMapper.insert(account);
            // 返回新增的用户信息
            dbAdmin = adminMapper.selectByUsername(account.getUsername());
            return dbAdmin;
        } catch (Exception e) {
            throw new ServiceException("488", "注册失败");
        }
    }

    @Override
    public void findPassword(Account account) {
        // 首先，判断用户输入的账号是否存在，数据库中用户名是唯一的
        Admin dbAdmin = adminMapper.selectByUsername(account.getUsername());
        if (dbAdmin == null) {
            // 用户名不存在，抛出自定义异常
            throw new ServiceException("422", "管理员未注册！");
        }
        try {


            // 直接随机生成密码，然后发邮件就行
            int passwordLength = 8;
            String password = RandomUtil.generateRandomPassword(passwordLength);
            System.out.println("生成的随机密码是: " + password);

            account.setPassword(DigestUtils.md5Hex(password));

            // 发送邮件
            MailUtil mailUtil = new MailUtil();
            String recipient = account.getEmail();
            Mail mail = new Mail();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mail.setRecipient(recipient);
            mail.setSubject("并州电子数码商城 \n 密码重置通知 \n" + sdf + "\n");
            mail.setContent("亲爱的用户：您好！\n" +
                    "\n" + "    您收到这封电子邮件是因为您 (也可能是某人冒充您的名义) 申请了修改账号密码。假如这不是您本人所申请, 请不用理会这封电子邮件, 但是如果您持续收到这类的信件骚扰, 请您尽快联络管理员。\n" +
                    "\n" +
                    "   您的密码已重置，新密码为： \n" + "\n  " +
                    password + "\n\n"
            );
            mailUtil.sendSimpleMail(mail);


            adminMapper.updatePassword(account);
        } catch (ServiceException e) {
            throw new ServiceException("423", "修改密码失败");
        }
    }

    @Override
    public void update(Account admin) {
        try {
            adminMapper.update(admin);
        } catch (ServiceException e) {
            throw new ServiceException("404", "修改失败!");
        }
    }

    @Override
    public Account getUserInfo(Integer id) {
        try {
            return adminMapper.getUserInfo(id);
        } catch (ServiceException e) {
            throw new ServiceException("404", "获取用户信息失败!");
        }
    }

    @Override
    public List<Admin> selectAll() {
        try {
            return adminMapper.selectAll();
        } catch (ServiceException e) {
            throw new ServiceException("404", "获取所有用户信息失败!");
        }
    }

    @Override
    public void changePassword(Account account) {
        // 首先，判断用户输入的账号是否存在，数据库中用户名是唯一的
        Admin dbAdmin = adminMapper.selectById(account.getId());
        if (dbAdmin == null) {
            // 用户名不存在，抛出自定义异常
            throw new ServiceException("404", "管理员未注册！");
        }
        // 判断用户输入的旧密码是否正确
        if (!dbAdmin.getPassword().equals(account.getPassword())) {
            // 旧密码不正确，抛出自定义异常
            throw new ServiceException("488", "旧密码不正确！");
        }
        // 修改密码
        dbAdmin.setPassword(account.getNewPassword());
        // 更新数据库中的管理员信息
        try {
            int row = adminMapper.changePassword(dbAdmin);
            if (row > 0) {
                // 修改成功
                // 让之前的账号token过期
                // 生成新的token
                String token = TokenUtils.genToken(dbAdmin.getId().toString(), dbAdmin.getPassword());
                dbAdmin.setToken(token);
            }
        } catch (ServiceException e) {
            throw new ServiceException("488", "修改密码失败!");
        }
    }
}
